package com.cloud.xtools.common.redis;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class RedisService {

    private final RedisTemplate<String, Object> redisTemplate;

    // 删除 key
    public void delete(String key) {

        redisTemplate.delete(key);
    }

    // 保存字符串
    public void setString(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    // 保存字符串（带过期时间）
    public void setString(String key, Object value, long timeout) {
        redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
    }

    // 获取字符串
    public Object getString(String key) {

        return redisTemplate.opsForValue().get(key);
    }

    // 保存 Hash 数据
    public void setHash(String key, String hashKey, Object value) {

        redisTemplate.opsForHash().put(key, hashKey, value);
    }

    // 获取 Hash 数据
    public Object getHash(String key, String hashKey) {

        return redisTemplate.opsForHash().get(key, hashKey);
    }

    // 删除 Hash 键
    public void deleteHash(String key, String hashKey) {

        redisTemplate.opsForHash().delete(key, hashKey);
    }

    // 添加到 List
    public void pushToList(String key, Object value) {

        redisTemplate.opsForList().leftPush(key, value);
    }

    // 获取 List
    public List<Object> getList(String key, long start, long end) {

        return redisTemplate.opsForList().range(key, start, end);
    }

    // 添加到 Set
    public void addToSet(String key, Object value) {

        redisTemplate.opsForSet().add(key, value);
    }

    // 获取 Set
    public Set<Object> getSet(String key) {

        return redisTemplate.opsForSet().members(key);
    }
}
